package com.paypalpay.controller.interfaces;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.paypalpay.entity.common.DevicePackageCoverPicture;
import com.paypalpay.entity.common.DevicePackageMarketingStrategy;
import com.paypalpay.entity.common.InternationalPayPackage;
import com.paypalpay.external.entity.mcc.request.RequestMcc;
import com.paypalpay.external.entity.mcc.request.RequestMccData;
import com.paypalpay.external.entity.mcc.response.ResponseMcc;
import com.paypalpay.external.entity.mcc.response.ResponseMccData;
import com.paypalpay.external.entity.mcc.response.ResponseMccTradeData;
import com.paypalpay.external.utils.UtilsInterfacesPackage;
import com.paypalpay.service.InternationalPayPackageService;
import com.paypalpay.service.SequenceService;
import com.paypalpay.util.wx.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 前端商城根据mcc过来取设备详情页的套餐信息的类
 *
 * @author lm
 * @date 2018/8/30
 */
@RestController
@Api(description = "前端商城获取详情页接口")
public class GetDeviceDetailsBymccController {
    @Autowired
    private HttpSession session;
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private InternationalPayPackageService internationalPayPackageService;

    @CrossOrigin
    @RequestMapping(value = "/getDeviceDetails", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "领科商城详情页", response = ResponseMcc.class)
    public String getDetails(@ApiParam @RequestBody RequestMcc requestMcc) {

        String requestStr = JSON.toJSONString(requestMcc);
        System.out.println("前端请求报文是：" + requestStr);

        String openId = (String) session.getAttribute("openId");
        String deviceId = (String) session.getAttribute("deviceId");
        String deviceType = (String) session.getAttribute("deviceType");
        // 1，生成流水号
        String ConnSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());

        //验证签名
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        //开始解析报文
        RequestMcc requestPackage = JSONArray.parseObject(requestStr, RequestMcc.class);
        String requestSign = requestPackage.getSign();
        if (requestPackage.getSign() == null) {

            System.out.println("请求报文不合法:sign为空");
            String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
            return jsonString;
        } else {
            System.out.println("请求的签名是：" + requestSign);
            RequestMccData requestData = requestPackage.getData();
            if (requestPackage.getData() == null) {
                System.out.println("请求报文不合法:data为空");
                String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                return jsonString;
            } else {
                String partnerCode = requestData.getPartnerCode();
                String connSeqNo = requestData.getConnSeqNo();
                String token = requestData.getToken();
                String tradeTime = requestData.getTradeTime();
                String tradeType = requestData.getTradeType();
                //获取到前端请求的lang的语言 en/cn
                String lang = requestData.getLang();
                if (partnerCode == null || partnerCode.length() <= 0 || connSeqNo == null || connSeqNo.length() <= 0 || token == null || token.length() <= 0 || tradeTime == null || tradeTime.length() <= 0 || lang == null || lang.length() <= 0) {
                    //参数不全,回复报文
                    System.out.println("请求报文不合法:参数不全！");
                    String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                    return jsonString;
                } else {
                    // 将请求体json转成String
                    String str = JSON.toJSONString(requestData);
                    // 将Str拿去计算签名
                    String sign = utils.calculateSignature(str);
                    System.out.println("计算的签名是：" + sign);
                    // 把请求中的mcc取出来啊
                    String mccRequest = requestData.getTradeData().getMcc();
                    if (mccRequest == null || mccRequest.length() <= 0) {
                        //参数不齐，回复报文
                        System.out.println("请求报文不合法:参数不全！");
                        String jsonString = utils.dataWeiKong(ConnSeqNo, curtime);
                        return jsonString;
                    } else {
                        // 验证签名：
                        if (!requestSign.equalsIgnoreCase(sign)) {
                            // 如果收到的签名跟算出的签名相同才可以回复正确的报文
                            System.out.println("请求报文签名验证失败");
                            String jsonString = utils.signatureFailMessage(connSeqNo, tradeTime, partnerCode, token, deviceId, deviceType);
                            return jsonString;
                        } else {
                            //签名通过了
                            System.out.println("取到的mcc是多少：" + mccRequest);
                            String coverCountryCode = null;
                            String packageCode = "";
                            String packageName = "";
                            String packageNameEN = "";
                            String packageType = "";
                            String buyType = "";
                            String flow = "";
                            String orderPeriod = "";
                            String packageTextDesc = "";
                            String packageTextDescEN = "";
                            //在详情页订图上面显示的国家名字，如：新马泰
                            String countryNameDetails = "";
                            String countryNameDetailsEN = "";
                            String packageDetailsDesc = "";
                            String packageDetailsDescEN = "";
                            String packageDetailsAdd = "";
                            String packageDetailsAddEN = "";

                            String pictureIndex = null;
                            String pictureDetails = null;
                            String packageImgDesc = null;
                            String packageImgDescEN = null;

                            String strategyCode = "";
                            String salePriceCNY="";
                            String salePriceUSD="";
                            String strategyDescCNY="";
                            String strategyDescUSD="";


                            List<ResponseMccTradeData> tradeData = new ArrayList<ResponseMccTradeData>();
                            ResponseMccTradeData trade = null;
                            // 1,从PartnerPackage数据库把数据取出来
                            List<InternationalPayPackage> packagesList = internationalPayPackageService.queryPackagesByMcc(mccRequest, partnerCode);
                            // List<InternationalPayPackage> packagesList = internationalPayPackageService.queryPackagesByMcc(mccRequest);
                            // 1,1,从InternationalPayPackage表中把图片信息取出来
                            for (InternationalPayPackage p : packagesList) {
                                coverCountryCode = p.getCoverCountryCode();
                                System.out.println("是多少：" + coverCountryCode);
                                packageCode = p.getPackageCode();
                                packageName = p.getPackageName();
                                packageNameEN = p.getPackageNameEN();
                                packageType = p.getPackageType();
                                buyType = p.getBuyType();
                                orderPeriod = p.getOrderPeriod();
                                flow = p.getFlow();
                                packageTextDesc = p.getPackageTextDesc();
                                packageTextDescEN = p.getPackageTextDescEN();
                                countryNameDetails = p.getCountryNameDetails();
                                countryNameDetailsEN = p.getCountryNameDetailsEN();
                                packageDetailsDesc = p.getPackageDetailsDesc();
                                packageDetailsDescEN = p.getPackageDetailsDescEN();
                                packageDetailsAdd = p.getPackageDetailsAdd();
                                packageDetailsAddEN = p.getPackageDetailsAddEN();

                                // 1,从CoverPicture表中把图片信息取出来 ,packageCode,partnerCode
                                List<DevicePackageCoverPicture> pictureList = internationalPayPackageService.queryPictureInfo(packageCode, partnerCode);
                                for (DevicePackageCoverPicture covers : pictureList) {
                                    pictureIndex = covers.getPictureIndex();
                                    pictureDetails = covers.getPictureDetails();
                                    packageImgDesc = covers.getPackageImgDesc();
                                    packageImgDescEN = covers.getPackageImgDescEN();
                                }

                                // 2,从DevicePackageMarketingStrategy表中把营销信息取出来
                                List<DevicePackageMarketingStrategy> strategyList = internationalPayPackageService.queryDeviceStrategy(packageCode, partnerCode);
                                //List<DevicePackageMarketingStrategy> strategyList = internationalPayPackageService.queryDeviceStrategy(packageCode);
                                for (DevicePackageMarketingStrategy strategy : strategyList) {
                                    strategyCode = strategy.getStrategyCode();
                                    salePriceCNY=strategy.getSalePriceCNY();
                                    salePriceUSD=strategy.getSalePriceUSD();
                                    strategyDescCNY=strategy.getStrategyDescCNY();
                                    strategyDescUSD=strategy.getStrategyDescUSD();
                                }
                                // 5,给TradeData赋值
                                trade = new ResponseMccTradeData();
                                trade.setDeviceId(deviceId);
                                trade.setDeviceType(deviceType);
                                // 有就传没有就传空
                                trade.setOpenId(openId);
                                trade.setPackageCode(packageCode);
                                trade.setPackageType(packageType);
                                trade.setBuyType(buyType);
                                //trade.setOrderUnit(orderUnit);packageType
                                trade.setOrderUnit(packageType);
                                trade.setOrderPeriod(orderPeriod);
                                trade.setFlow(flow);
                                trade.setPictureIndex(pictureIndex);
                                trade.setPictureDetails(pictureDetails);
                                trade.setStrategyCode(strategyCode);
                                // strategyCode取值：1,热销商品；2,低价促销；3，为正常销售；4既是热销又是低价促销

                                if ("en".equalsIgnoreCase(lang)) {
                                    if (strategyCode.equals("1") || strategyCode.equals("3")) {
                                        trade.setSalePrice(salePriceUSD);
                                    } else if (strategyCode.equals("2") || strategyCode.equals("4")) {
                                        trade.setStrategyDesc(strategyDescUSD);
                                    }
                                } else {
                                    if (strategyCode.equals("1") || strategyCode.equals("3")) {
                                        trade.setSalePrice(salePriceCNY);
                                    } else if (strategyCode.equals("2") || strategyCode.equals("4")) {
                                        trade.setStrategyDesc(strategyDescCNY);
                                    }
                                }

                                trade.setMcc(mccRequest);
                                if (lang.equals("en")) {
                                    trade.setPackageName(packageNameEN);
                                    trade.setPackageTextDesc(packageTextDescEN);
                                    trade.setCountryNameDetails(countryNameDetailsEN);
                                    trade.setPackageDetailsDesc(packageDetailsDescEN);
                                    trade.setPackageDetailsAdd(packageDetailsAddEN);
                                    trade.setPackageImgDesc(packageImgDescEN);
                                } else {
                                    trade.setPackageName(packageName);
                                    trade.setPackageTextDesc(packageTextDesc);
                                    trade.setCountryNameDetails(countryNameDetails);
                                    trade.setPackageDetailsDesc(packageDetailsDesc);
                                    trade.setPackageDetailsAdd(packageDetailsAdd);
                                    trade.setPackageImgDesc(packageImgDesc);
                                }
                                tradeData.add(trade);
                            }
                            // 以上循环结束。
                            // 6，给Data赋值
                            ResponseMccData data = new ResponseMccData();
                            data.setConnSeqNo(connSeqNo);
                            data.setPartnerCode(partnerCode);
                            data.setToken(token);
                            data.setTradeType(tradeType);
                            data.setTradeTime(curtime);
                            data.setTradeRstCode(1000);
                            data.setTradeRstMessage("success");
                            data.setTradeData(tradeData);

                            // 6，给ResponsePackage赋值
                            ResponseMcc resPackages = new ResponseMcc();
                            resPackages.setData(data);
                            resPackages.setSign(MD5.calcMD5(JSON.toJSONString(data)));

                            String jsonString = JSON.toJSONString(resPackages);
                            // 返回给调用者的报文
                            System.out.println("响应报文：" + jsonString);
                            return jsonString;

                        }
                    }
                }
            }
        }
    }
}